import { Select } from 'antd';
import { useEffect, useState } from 'react';
import styled from 'styled-components';
import { ISelectProps } from './types';

const StyledSelect = styled(Select)`
  width: 100%;
  .ant-select-selection-item-remove > .anticon {
    padding-left: 10px;
  }
`;
export default function NativeSelect({
  options,
  value,
  disabled = false,
  multiple = false,
  onChange,
}: ISelectProps) {
  const [valueSelect, setValueSelect] = useState<string[]>([]);
  useEffect(() => {
    const defaultValue = [];
    setValueSelect([]);
    if (Array.isArray(value)) {
      setValueSelect(value);
    } else {
      if (value) {
        defaultValue.push(value);
        setValueSelect(defaultValue);
      }
    }
  }, [options, value, multiple, disabled]);
  if (options.length === 0) return <></>;

  const optionsList: any = options;
  const handleChange = (value, option) => {
    if (Array.isArray(option)) {
      const array = [];
      option.forEach((item) => array.push(item.value));
      setValueSelect(array);
      onChange(array);
    } else {
      setValueSelect(value);
      onChange(option.value);
    }
  };
  // 是否开启多选
  const mode = multiple ? 'multiple' : undefined;

  return (
    <StyledSelect
      popupMatchSelectWidth={false}
      mode={mode}
      value={valueSelect}
      disabled={disabled}
      placeholder='请选择'
      onChange={handleChange}
      options={optionsList}
      allowClear={multiple}
    />
  );
}
